//
//  GuidePageViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/14.
//

import UIKit
import YYKit

class GuidePageViewController: BaseViewController {
    var logoImgView: UIImageView!
    var pageScrollView: LaunchScrollView!
    var languageView: LanguageView!
    var jumpAppBtn: UIButton! //立即体验btn
    var protocolLab: YYLabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.isHidden = true
        logoImgView = UIImageView()
        logoImgView.image = UIImage.init(named: "title_logo")
        logoImgView.contentMode = .scaleAspectFit
        view.addSubview(logoImgView)
        
        _ = XTManageCenter.getAppleLanguages()
        pageScrollView = LaunchScrollView()
        view.addSubview(pageScrollView)
        
        //切换语言
        languageView = LanguageView()
        languageView.callBack = {[weak self] tag in
            self?.changeLanguage(tag: tag)
        }
        view.addSubview(languageView)
        
        //立即体验
        jumpAppBtn = UIButton()
        jumpAppBtn.setup_titleLabel(text: MMLocalizedString("launch_app", comment: "立即体验"))
        jumpAppBtn.setup_titleColor(color: Theme.whiteColor)
        jumpAppBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        jumpAppBtn.layer.cornerRadius = 8
        jumpAppBtn.layer.masksToBounds = true
        jumpAppBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColor), for: .normal)
        jumpAppBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColorHighLightColor), for: .highlighted)
        jumpAppBtn.addTarget(self, action: #selector(self.jumpAppBtnAction), for: .touchUpInside)
        view.addSubview(jumpAppBtn)
        
        protocolLab = YYLabel(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 44))
        protocolLab.numberOfLines = 0
        protocolLab.textAlignment = .center
        self.view.addSubview(protocolLab)
        
        self.initailValue()
        self.addSnpLayout()
        self.requestBaseParameter()
    }
    
    private func addSnpLayout(){
        logoImgView.snp.makeConstraints { make in
            make.top.equalTo(NavBarHight + 10)
            make.width.equalTo(169)
            make.height.equalTo(54)
            make.centerX.equalTo(kScreenWidth/2)
        }
        
        pageScrollView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.lessThanOrEqualTo(logoImgView.snp.bottom).offset(64)
            make.height.equalTo(348)
        }
        
        languageView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.greaterThanOrEqualTo(pageScrollView.snp.bottom).offset(40)
            make.height.equalTo(46)
        }
        
        jumpAppBtn.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.height.equalTo(46)
            make.top.equalTo(languageView.snp.bottom).offset(20)
        }
        
//        self.protocolLab.sizeToFit()
//        var tempWW = self.protocolLab.frame.size.width
//        if tempWW > (kScreenWidth - 28) {
//            tempWW = kScreenWidth - 28
//        }
        protocolLab.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.bottom.equalTo(-IphoneXMarginBottom-20)
            make.top.equalTo(jumpAppBtn.snp.bottom).offset(20)
            make.height.greaterThanOrEqualTo(40)
        }
    }
    
   private func initailValue(){
        let service = MMLocalizedString("launch_private", comment: "隐私条款")
        let privacy = MMLocalizedString("launch_protocol", comment: "法律声明")
        let str = String(format: MMLocalizedString("launch_agree", comment: "按下立即体验代表您已阅读并同意%@和%@"), service, privacy)
        let serviceLoc = str.findSubStringLocation(subString: service)
        let privacyLoc = str.findSubStringLocation(subString: privacy)

        let attStr = NSMutableAttributedString.init(string: str)
        attStr.lineSpacing = 8
        attStr.setTextHighlight(NSRange.init(location: 0, length: str.count), color: Theme.line8Color, backgroundColor: UIColor.clear, tapAction: { (containerView, attr, tRange, rect) in
        })
        
        if serviceLoc > 0 {
            attStr.setTextHighlight(NSRange.init(location: serviceLoc, length: service.count), color: Theme.mainColor, backgroundColor: UIColor.clear, tapAction: { (containerView, attr, tRange, rect) in
                self.didTapProtocoAction()
            })
        }
        
        if privacyLoc > 0 {
            attStr.setTextHighlight(NSRange.init(location: privacyLoc, length: privacy.count), color: Theme.mainColor, backgroundColor: UIColor.clear, tapAction: { (containerView, attr, tRange, rect) in
                self.didTapPrivateAction()
            })
        }
        self.protocolLab.attributedText = attStr
        self.protocolLab.textAlignment = .center
    }
    
    private func changeLanguage(tag: NSInteger) {
        switch tag {
            case 0:
                //繁体中文
                XTManageCenter.setLocalDataString(aKey: UtilCenter.kAppLanguage, aValue: AppLanguage.chinese_hk.rawValue)
            case 1:
                //简体
                XTManageCenter.setLocalDataString(aKey: UtilCenter.kAppLanguage, aValue: AppLanguage.chinese_simple.rawValue)
            case 2:
                //english
                XTManageCenter.setLocalDataString(aKey: UtilCenter.kAppLanguage, aValue: AppLanguage.english.rawValue)
            default:
                ()
        }
        self.refreashLanguage()
    }
    
    private func refreashLanguage(){
        self.pageScrollView.reloadData()
        self.languageView.collectionView.reloadData()
        self.jumpAppBtn.setup_titleLabel(text: MMLocalizedString("launch_app", comment: "立即体验"))
        self.initailValue()
    }
    
    ///基础参数
   public func requestBaseParameter() {
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.baseParameter(param: ["":""]), objectType: BaseParameterModel.self) { data in
            let resultObj = data as! BaseParameterModel
            if resultObj.code == "1" && resultObj.data != nil {
                XTManageCenter.setLocalPlaceParameter(paramData: resultObj.data)
            }else{
           
            }
        } error: { err in
           
        }
    }
    
    
    ///隐私条款
    @objc func didTapProtocoAction(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.privacyGreement(param: [:]), objectType: ProtocolResData.self) { data in
            let resultObj = data as? ProtocolResData
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            let vc = WebViewController()
            vc.localHtmlStr = resultObj?.data?.content ?? ""
            vc.titleStr = MMLocalizedString("launch_private", comment: "隐私条款")
            self.navigationController?.pushViewController(vc, animated: true)
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///法律声明
    @objc func didTapPrivateAction(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.indexLegalStatement, objectType: ProtocolResData.self) { data in
            let resultObj = data as? ProtocolResData
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            let vc = WebViewController()
            vc.localHtmlStr = resultObj?.data?.content ?? ""
            vc.titleStr = MMLocalizedString("launch_protocol", comment: "法律声明")
            self.navigationController?.pushViewController(vc, animated: true)
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }

    @objc func jumpAppBtnAction(){
        XTManageCenter.setLocalDataString(aKey: UtilCenter.isFristOpen, aValue: "0")
        let tabbarVC = BaseTabbarController()
        UIApplication.shared.keyWindow?.rootViewController = tabbarVC
        tabbarVC.selectedIndex = 0
    }
}
